<template>
  <div class="playback-container">
    <a-row :gutter="16">
      <!-- 视频播放器 -->
      <a-col :span="20">
        <a-card title="录像回放" class="player-panel" size="small">
          <div class="video-container">
            <div v-if="!isPlaying" class="video-placeholder">
              <div class="placeholder-content">
                <video-camera-outlined style="font-size: 48px; color: #ccc;" />
                <p>选择录像文件开始回放</p>
              </div>
            </div>
            
            <div v-else class="video-player">
              <!-- WebRTC视频播放器 -->
              <video
                ref="videoElement"
                autoplay
                :muted="audioMuted"
                playsinline
                style="width: 100%; height: 70vh; background: #000;"
                @volumechange="handleVolumeChange"
              ></video>
            </div>
            
            <!-- 播放控制条 - 始终显示 -->
            <div class="video-controls">
              <div class="control-row">
                <a-space>
                  <a-button
                    type="text"
                    :icon="isPaused ? h(PlayCircleOutlined) : h(PauseCircleOutlined)"
                    @click="togglePlayPause"
                    :disabled="!isPlaying"
                  />
                  <a-button
                    type="text"
                    :icon="h(PoweroffOutlined)"
                    @click="stopPlayback"
                    :disabled="!isPlaying"
                  />
                  <a-divider type="vertical" style="background: rgba(255,255,255,0.3)" />
                  <!-- 音频控制按钮 -->
                  <a-button
                    type="text"
                    :icon="audioMuted ? h(SoundOutlined) : h(SoundFilled)"
                    @click="toggleAudio"
                    :disabled="!isPlaying"
                    :style="{ color: audioMuted ? '#999' : '#1890ff' }"
                    title="音频开关"
                  />
                  <!-- 音量控制 -->
                  <div v-if="!audioMuted" class="volume-control">
                    <a-slider
                      v-model:value="audioVolume"
                      :min="0"
                      :max="1"
                      :step="0.1"
                      :style="{ width: '60px', margin: '0' }"
                      @change="handleVolumeChange"
                      :tip-formatter="(value) => Math.round(value * 100) + '%'"
                    />
                  </div>
                </a-space>
                
                <div class="time-info">
                  <span>{{ formatDuration(currentTime) }} / {{ formatDuration(totalDuration) }}</span>
                  <span v-if="audioEnabled && isPlaying" class="audio-status">
                    <a-tag :color="audioMuted ? 'default' : 'blue'" size="small">
                      {{ audioMuted ? '静音' : '音频' }}
                    </a-tag>
                  </span>
                </div>
                
                <a-space>
                  <a-select
                    v-model:value="playbackSpeed"
                    style="width: 80px"
                    size="small"
                    @change="handleSpeedChange"
                    :disabled="!isPlaying"
                  >
                    <a-select-option :value="0.25">0.25x</a-select-option>
                    <a-select-option :value="0.5">0.5x</a-select-option>
                    <a-select-option :value="1">1x</a-select-option>
                    <a-select-option :value="2">2x</a-select-option>
                    <a-select-option :value="4">4x</a-select-option>
                    <a-select-option :value="8">8x</a-select-option>
                  </a-select>
                </a-space>
              </div>
              
              <!-- 进度条 - 只在有录像片段时显示 -->
              <div v-if="timelineSegments.length > 0" class="progress-row">
                <div class="timeline-container">
                  <!-- 时间轴背景 -->
                  <div class="timeline-background"></div>
                  
                  <!-- 录像片段 -->
                  <div class="timeline-segments">
                    <div
                      v-for="(segment, index) in timelineSegments"
                      :key="index"
                      class="timeline-segment"
                      :class="getSegmentClass(segment.event_type || segment.event)"
                      :style="{
                        left: segment.leftPercent + '%',
                        width: segment.widthPercent + '%'
                      }"
                      @click="seekToSegment(segment)"
                      :title="`${getEventTypeName(segment.event_type || segment.event)}: ${formatTime(segment.start_time)} - ${formatTime(segment.end_time)}`"
                    ></div>
                  </div>
                  
                  <!-- 播放进度指示器 -->
                  <div
                    v-if="isPlaying"
                    class="timeline-progress"
                    :style="{ left: progress + '%' }"
                  ></div>
                  
                  <!-- 时间刻度 -->
                  <div class="timeline-scale">
                    <div
                      v-for="(tick, index) in timelineTicks"
                      :key="index"
                      class="timeline-tick"
                      :style="{ left: tick.percent + '%' }"
                    >
                      <div class="tick-mark"></div>
                      <div class="tick-label">{{ tick.label }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
      
      <!-- 录像搜索面板 -->
      <a-col :span="4">
        <a-card title="录像搜索" class="search-panel" size="small">
          <a-form layout="vertical" class="compact-form">
            <a-form-item label="日期" class="form-item-compact">
              <a-date-picker
                v-model:value="searchForm.date"
                format="YYYY-MM-DD"
                style="width: 100%"
                size="small"
                placeholder="选择日期"
              />
            </a-form-item>
            
            <a-form-item label="开始时间" class="form-item-compact">
              <a-time-picker
                v-model:value="searchForm.startTime"
                format="HH:mm:ss"
                style="width: 100%"
                size="small"
                placeholder="开始时间"
              />
            </a-form-item>
            
            <a-form-item label="结束时间" class="form-item-compact">
              <a-time-picker
                v-model:value="searchForm.endTime"
                format="HH:mm:ss"
                style="width: 100%"
                size="small"
                placeholder="结束时间"
              />
            </a-form-item>
            
            <a-form-item label="事件类型" class="form-item-compact">
              <div class="event-type-checkboxes">
                <a-checkbox
                  v-model:checked="searchForm.eventTypes.continuous"
                  class="event-checkbox"
                >
                  连续录像
                </a-checkbox>
                <a-checkbox
                  v-model:checked="searchForm.eventTypes.motion"
                  class="event-checkbox"
                >
                  动态检测
                </a-checkbox>
                <a-checkbox
                  v-model:checked="searchForm.eventTypes.alarm"
                  class="event-checkbox"
                >
                  报警录像
                </a-checkbox>
                <a-checkbox
                  v-model:checked="searchForm.eventTypes.manual"
                  class="event-checkbox"
                >
                  手动录像
                </a-checkbox>
              </div>
            </a-form-item>
            
            <a-form-item class="form-item-compact">
              <a-space direction="vertical" style="width: 100%">
                <a-button type="primary" @click="searchRecords" :loading="searching" size="small" block>
                  搜索录像
                </a-button>
                <a-button @click="resetSearch" size="small" block>重置</a-button>
              </a-space>
            </a-form-item>
          </a-form>
          
          <!-- 搜索结果统计 -->
          <div v-if="totalRecords > 0" class="search-stats">
            <a-statistic
              title="找到录像"
              :value="totalRecords"
              suffix="个片段"
              :value-style="{ fontSize: '14px' }"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, h } from 'vue'
import { message } from 'ant-design-vue'
import { 
  VideoCameraOutlined, 
  PlayCircleOutlined, 
  PauseCircleOutlined,
  PoweroffOutlined,
  SoundOutlined,
  SoundFilled
} from '@ant-design/icons-vue'
import recordApi from '../../api/record'
import { JsonRpcClient } from '../../utils/jsonRpc'
import dayjs from 'dayjs'

const recordList = ref([])
const loading = ref(false)
const searching = ref(false)
const totalRecords = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

const isPlaying = ref(false)
const isPaused = ref(false)
const currentPlayback = ref(null)
const playbackId = ref(null)
const playbackSpeed = ref(1)

// 音频控制状态
const audioEnabled = ref(false)
const audioMuted = ref(true)
const audioVolume = ref(0.8)

const currentTime = ref(0)
const totalDuration = ref(0)
const progress = ref(0)

// 时间轴相关数据
const timelineSegments = ref([])
const timelineTicks = ref([])
const timelineTooltip = reactive({
  visible: false,
  x: 0,
  y: 0,
  text: ''
})
const searchStartTime = ref(0)
const searchEndTime = ref(0)

const videoElement = ref(null)
let peerConnection = null
let webSocket = null
let rpcClient = null

const searchForm = reactive({
  channel: 0,
  date: dayjs(),
  startTime: dayjs().hour(0).minute(0).second(0),
  endTime: dayjs().hour(23).minute(59).second(59),
  eventTypes: {
    continuous: true,
    motion: true,
    alarm: true,
    manual: true
  }
})

const eventTypeMap = {
  'schedule': '连续录像',
  'motion': '动态检测', 
  'alarm': '报警录像',
  'manual': '手动录像',
  // 兼容数字格式
  0: '连续录像',
  1: '动态检测',
  2: '报警录像',
  3: '手动录像'
}

const formatTime = (timestamp) => {
  if (!timestamp) return 'Invalid Date'
  
  // 如果是数字，当作Unix时间戳处理
  if (typeof timestamp === 'number') {
    return dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')
  }
  
  // 如果是字符串，当作ISO 8601格式处理
  if (typeof timestamp === 'string') {
    return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
  }
  
  return 'Invalid Date'
}

const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '未知大小'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = Math.floor(seconds % 60)
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const formatProgressTip = (value) => {
  const time = (totalDuration.value * value) / 100
  return formatDuration(time)
}

const getEventTypeName = (eventType) => {
  return eventTypeMap[eventType] || '未知'
}

const getSegmentClass = (eventType) => {
  const typeMap = {
    'schedule': 'segment-type-0',
    'motion': 'segment-type-1',
    'alarm': 'segment-type-2', 
    'manual': 'segment-type-3',
    // 兼容数字格式
    0: 'segment-type-0',
    1: 'segment-type-1',
    2: 'segment-type-2',
    3: 'segment-type-3'
  }
  return typeMap[eventType] || 'segment-type-0'
}

const searchRecords = async () => {
  if (!searchForm.date) {
    message.error('请选择日期')
    return
  }
  
  searching.value = true
  try {
    // 构建完整的开始和结束时间
    let startTime, endTime
    
    if (searchForm.startTime && searchForm.endTime) {
      // 合并日期和时间
      startTime = searchForm.date
        .hour(searchForm.startTime.hour())
        .minute(searchForm.startTime.minute())
        .second(searchForm.startTime.second())
      
      endTime = searchForm.date
        .hour(searchForm.endTime.hour())
        .minute(searchForm.endTime.minute())
        .second(searchForm.endTime.second())
        
      // 如果结束时间小于开始时间，说明跨天了，结束时间加一天
      if (endTime.isBefore(startTime)) {
        endTime = endTime.add(1, 'day')
      }
    } else {
      // 默认使用全天
      startTime = searchForm.date.startOf('day')
      endTime = searchForm.date.endOf('day')
    }
    
    searchStartTime.value = startTime.unix()
    searchEndTime.value = endTime.unix()
    
    // 构建事件类型数组
    const selectedEventTypes = []
    if (searchForm.eventTypes.continuous) selectedEventTypes.push(0)
    if (searchForm.eventTypes.motion) selectedEventTypes.push(1)
    if (searchForm.eventTypes.alarm) selectedEventTypes.push(2)
    if (searchForm.eventTypes.manual) selectedEventTypes.push(3)
    
    // 将事件类型数组转换为后端期望的单一字符串
    let eventType = 'all'
    if (selectedEventTypes.length > 0 && selectedEventTypes.length < 4) {
      const typeMap = {
        0: 'schedule',
        1: 'motion', 
        2: 'alarm',
        3: 'manual'
      }
      eventType = selectedEventTypes.length === 1 ? 
        typeMap[selectedEventTypes[0]] : 'all'
    }
    
    const searchParams = {
      channel: searchForm.channel,
      start_time: startTime.toISOString(),
      end_time: endTime.toISOString(), 
      event_type: eventType,
      stream_type: 0 // 默认使用主码流
    }
    
    const searchResponse = await recordApi.searchRecords(searchParams)
    if (searchResponse.error) {
      message.error(searchResponse.error.message || '搜索失败')
      return
    }
    
    // 直接加载录像列表用于生成时间轴
    await loadRecordList()
    generateTimeline()
    
    if (recordList.value.length > 0) {
      message.success(`找到 ${recordList.value.length} 个录像片段`)
    } else {
      message.info('没有找到录像文件')
    }
    
  } catch (error) {
    console.error('搜索录像失败:', error)
    message.error('搜索录像失败')
  } finally {
    searching.value = false
  }
}

const loadRecordList = async () => {
  loading.value = true
  try {
    const listParams = {
      page: currentPage.value,
      page_size: pageSize.value,
      sort_by: 'start_time',
      sort_order: 'desc'
    }
    
    const response = await recordApi.getRecordList(listParams)
    if (response.error) {
      message.error(response.error.message || '加载录像列表失败')
      return
    }
    
    recordList.value = response.result.records || []
    totalRecords.value = response.result.total_count || 0
    
  } catch (error) {
    console.error('加载录像列表失败:', error)
    message.error('加载录像列表失败')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchForm.channel = 0
  searchForm.date = dayjs()
  searchForm.startTime = dayjs().hour(0).minute(0).second(0)
  searchForm.endTime = dayjs().hour(23).minute(59).second(59)
  searchForm.eventTypes = {
    continuous: true,
    motion: true,
    alarm: true,
    manual: true
  }
  recordList.value = []
  totalRecords.value = 0
  currentPage.value = 1
  timelineSegments.value = []
  timelineTicks.value = []
  
  // 重置时间轴为当天的24小时
  searchStartTime.value = dayjs().startOf('day').unix()
  searchEndTime.value = dayjs().endOf('day').unix()
  generateDefaultTimeline()
}

// 生成时间轴片段和刻度
const generateTimeline = () => {
  if (!searchStartTime.value || !searchEndTime.value || recordList.value.length === 0) {
    timelineSegments.value = []
    timelineTicks.value = []
    return
  }
  
  const totalTimespan = searchEndTime.value - searchStartTime.value
  
  // 生成录像片段 - 处理ISO时间格式
  timelineSegments.value = recordList.value.map(record => {
    const startTime = typeof record.start_time === 'string' ? 
      dayjs(record.start_time).unix() : record.start_time
    const endTime = typeof record.end_time === 'string' ? 
      dayjs(record.end_time).unix() : record.end_time
      
    const startOffset = startTime - searchStartTime.value
    const duration = endTime - startTime
    
    return {
      ...record,
      start_time: startTime,
      end_time: endTime,
      leftPercent: Math.max(0, (startOffset / totalTimespan) * 100),
      widthPercent: Math.max(0.1, (duration / totalTimespan) * 100)
    }
  })
  
  // 生成时间刻度
  generateTimelineTicks()
}

// 生成默认时间轴（显示24小时刻度）
const generateDefaultTimeline = () => {
  if (!searchStartTime.value || !searchEndTime.value) {
    const today = dayjs()
    searchStartTime.value = today.startOf('day').unix()
    searchEndTime.value = today.endOf('day').unix()
  }
  
  generateTimelineTicks()
}

// 生成时间轴刻度（每2小时一个刻度）
const generateTimelineTicks = () => {
  const totalTimespan = searchEndTime.value - searchStartTime.value
  const tickCount = 12 // 24小时分成12个刻度（2小时间隔）
  
  timelineTicks.value = []
  for (let i = 0; i <= tickCount; i++) {
    const percent = (i / tickCount) * 100
    const timestamp = searchStartTime.value + (totalTimespan * i / tickCount)
    const label = dayjs.unix(timestamp).format('HH:mm')
    
    timelineTicks.value.push({
      percent,
      label,
      timestamp
    })
  }
}

// 时间轴点击处理
const handleTimelineClick = (event) => {
  if (!searchStartTime.value || !searchEndTime.value) return
  
  const rect = event.currentTarget.getBoundingClientRect()
  const clickX = event.clientX - rect.left
  const percent = (clickX / rect.width) * 100
  
  // 查找点击位置对应的录像片段
  const clickedSegment = timelineSegments.value.find(segment => {
    return percent >= segment.leftPercent && percent <= segment.leftPercent + segment.widthPercent
  })
  
  if (clickedSegment) {
    seekToSegment(clickedSegment)
  }
}

// 定位到指定录像片段
const seekToSegment = async (segment) => {
  try {
    // 如果当前没有播放这个片段，先开始播放
    const currentFilename = currentPlayback.value?.file_name || currentPlayback.value?.filename
    const segmentFilename = segment.file_name || segment.filename || `${segment.file_id}.mp4`
    
    if (!isPlaying.value || currentFilename !== segmentFilename) {
      await startPlayback(segment)
      return
    }
    
    // 如果已在播放此片段，定位到片段开始位置
    if (rpcClient && webSocket && webSocket.readyState === WebSocket.OPEN && currentPlayback.value) {
      // 计算相对于当前录像开始的位置
      const currentRecordStart = typeof currentPlayback.value.start_time === 'string' ? 
        dayjs(currentPlayback.value.start_time).unix() : currentPlayback.value.start_time
      const targetPosition = segment.start_time - currentRecordStart
      
      await rpcClient.sendRequest('playback.seek', {
        position: Math.max(0, targetPosition)
      })
      
      const totalTimespan = searchEndTime.value - searchStartTime.value
      const segmentOffset = segment.start_time - searchStartTime.value
      progress.value = (segmentOffset / totalTimespan) * 100
      
      message.success(`定位到${getEventTypeName(segment.event)}录像`)
    }
  } catch (error) {
    console.error('定位录像片段失败:', error)
    message.error('定位录像片段失败: ' + error.message)
  }
}

// 时间轴鼠标悬停处理
const handleTimelineHover = (event) => {
  if (!searchStartTime.value || !searchEndTime.value) return
  
  const rect = event.currentTarget.getBoundingClientRect()
  const hoverX = event.clientX - rect.left
  const percent = (hoverX / rect.width) * 100
  
  const totalTimespan = searchEndTime.value - searchStartTime.value
  const timestamp = searchStartTime.value + (totalTimespan * percent / 100)
  
  // 查找悬停位置对应的录像片段
  const hoveredSegment = timelineSegments.value.find(segment => {
    return percent >= segment.leftPercent && percent <= segment.leftPercent + segment.widthPercent
  })
  
  timelineTooltip.visible = true
  timelineTooltip.x = event.clientX
  timelineTooltip.y = event.clientY - 40
  
  if (hoveredSegment) {
    timelineTooltip.text = `${getEventTypeName(hoveredSegment.event_type || hoveredSegment.event)}: ${formatTime(hoveredSegment.start_time)}`
  } else {
    timelineTooltip.text = formatTime(timestamp)
  }
}

const hideTimelineTooltip = () => {
  timelineTooltip.visible = false
}

const startPlayback = async (record) => {
  try {
    if (isPlaying.value) {
      await stopPlayback()
    }
    
    // 初始化WebSocket连接到回放端点
    if (!webSocket || webSocket.readyState !== WebSocket.OPEN) {
      await initWebSocketConnection()
    }
    
    // 设置当前播放的录像信息
    currentPlayback.value = record
    
    // 计算录像时长
    const startTime = typeof record.start_time === 'string' ? 
      dayjs(record.start_time).unix() : record.start_time
    const endTime = typeof record.end_time === 'string' ? 
      dayjs(record.end_time).unix() : record.end_time
    
    totalDuration.value = endTime - startTime
    currentTime.value = 0
    progress.value = 0
    
    // 初始化WebRTC连接
    await initWebRTCConnection()
    
    // 使用文件名而不是file_id来启动回放
    const filename = record.file_name || record.filename || `${record.file_id}.mp4`
    
    // 发送回放开始请求
    await rpcClient.sendRequest('playback.start', {
      filename: filename,
      speed: playbackSpeed.value,
      start_position: 0
    })
    
    isPlaying.value = true
    isPaused.value = false
    
    message.success('开始回放')
    
  } catch (error) {
    console.error('开始回放失败:', error)
    message.error('开始回放失败: ' + error.message)
  }
}

const stopPlayback = async () => {
  try {
    // 发送停止回放请求
    if (rpcClient && webSocket && webSocket.readyState === WebSocket.OPEN) {
      await rpcClient.sendRequest('playback.stop', {})
    }
    
    // 关闭WebRTC连接
    if (peerConnection) {
      peerConnection.close()
      peerConnection = null
    }
    
    // 关闭WebSocket连接
    if (webSocket) {
      webSocket.close()
      webSocket = null
      rpcClient = null
    }
    
    // 清理视频元素
    if (videoElement.value) {
      videoElement.value.srcObject = null
    }
    
    // 重置状态
    isPlaying.value = false
    isPaused.value = false
    currentPlayback.value = null
    playbackId.value = null
    currentTime.value = 0
    totalDuration.value = 0
    progress.value = 0
    
    // 重置音频状态
    audioEnabled.value = false
    audioMuted.value = true
    
    message.success('停止回放')
    
  } catch (error) {
    console.error('停止回放失败:', error)
    message.error('停止回放失败: ' + error.message)
  }
}

const togglePlayPause = async () => {
  if (!rpcClient || !webSocket || webSocket.readyState !== WebSocket.OPEN) return
  
  try {
    if (isPaused.value) {
      await rpcClient.sendRequest('playback.resume', {})
      isPaused.value = false
      message.success('恢复播放')
    } else {
      await rpcClient.sendRequest('playback.pause', {})
      isPaused.value = true
      message.success('暂停播放')
    }
  } catch (error) {
    console.error('播放控制失败:', error)
    message.error('播放控制失败: ' + error.message)
  }
}

const handleSpeedChange = async (speed) => {
  if (!rpcClient || !webSocket || webSocket.readyState !== WebSocket.OPEN) return
  
  try {
    await rpcClient.sendRequest('playback.setSpeed', {
      speed: speed
    })
    playbackSpeed.value = speed
    message.success(`播放速度: ${speed}x`)
    
  } catch (error) {
    console.error('设置播放速度失败:', error)
    message.error('设置播放速度失败: ' + error.message)
  }
}

// 音频控制方法
const toggleAudio = () => {
  audioMuted.value = !audioMuted.value
  if (videoElement.value) {
    videoElement.value.muted = audioMuted.value
    videoElement.value.volume = audioMuted.value ? 0 : audioVolume.value
  }
  
  const status = audioMuted.value ? '已静音' : '已开启'
  message.success(`音频${status}`)
}

const handleVolumeChange = (value) => {
  if (typeof value === 'number') {
    audioVolume.value = value
  }
  
  if (videoElement.value) {
    videoElement.value.volume = audioMuted.value ? 0 : audioVolume.value
  }
}


const handlePageChange = (page, size) => {
  currentPage.value = page
  pageSize.value = size
  loadRecordList()
}

const handlePageSizeChange = (_, size) => {
  currentPage.value = 1
  pageSize.value = size
  loadRecordList()
}

// 初始化WebSocket连接
const initWebSocketConnection = async () => {
  return new Promise((resolve, reject) => {
    try {
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const host = window.location.host
      
      // 获取登录时存储的token
      const token = localStorage.getItem('access_token')
      if (!token) {
        reject(new Error('未登录或token已过期'))
        return
      }
      
      // 通过URL参数传递token
      const wsUrl = `${protocol}//${host}/v1/webrtc/playback?token=${encodeURIComponent(token)}`
      
      webSocket = new WebSocket(wsUrl)
      rpcClient = new JsonRpcClient(webSocket)
      
      webSocket.onopen = () => {
        console.log('WebSocket连接已建立')
        
        // 注册WebRTC相关的方法处理器
        rpcClient.registerMethod('webrtc.offer', handleWebRTCOffer)
        rpcClient.registerMethod('webrtc.iceCandidate', handleWebRTCIceCandidate)
        
        resolve()
      }
      
      webSocket.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data)
          rpcClient.handleMessage(message)
        } catch (error) {
          console.error('处理WebSocket消息失败:', error)
        }
      }
      
      webSocket.onerror = (error) => {
        console.error('WebSocket错误:', error)
        reject(error)
      }
      
      webSocket.onclose = () => {
        console.log('WebSocket连接已关闭')
        if (isPlaying.value) {
          stopPlayback()
        }
      }
      
    } catch (error) {
      reject(error)
    }
  })
}

// 初始化WebRTC连接
const initWebRTCConnection = async () => {
  try {
    const config = {
      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
    }
    
    peerConnection = new RTCPeerConnection(config)
    
    // 处理接收到的媒体流
    peerConnection.ontrack = (event) => {
      console.log('接收到媒体流，音轨数:', event.streams[0].getAudioTracks().length)
      if (videoElement.value) {
        videoElement.value.srcObject = event.streams[0]
        // 检查是否有音频轨道
        const audioTracks = event.streams[0].getAudioTracks()
        audioEnabled.value = audioTracks.length > 0
        
        if (audioEnabled.value) {
          console.log('检测到音频轨道:', audioTracks[0].label)
          // 设置初始音频状态
          videoElement.value.muted = audioMuted.value
          videoElement.value.volume = audioMuted.value ? 0 : audioVolume.value
        } else {
          console.log('未检测到音频轨道')
          audioMuted.value = true
        }
      }
    }
    
    // 处理ICE连接状态变化
    peerConnection.oniceconnectionstatechange = () => {
      console.log('ICE连接状态:', peerConnection.iceConnectionState)
      if (peerConnection.iceConnectionState === 'failed') {
        message.error('网络连接失败，请检查网络设置')
      }
    }
    
    // 处理ICE候选
    peerConnection.onicecandidate = (event) => {
      if (event.candidate && rpcClient) {
        rpcClient.sendNotification('webrtc.iceCandidate', {
          candidate: event.candidate.candidate,
          sdpMLineIndex: event.candidate.sdpMLineIndex
        })
      }
    }
    
    // 发送ready信号
    await rpcClient.sendRequest('webrtc.ready', {})
    
  } catch (error) {
    console.error('初始化WebRTC连接失败:', error)
    throw error
  }
}

// 处理WebRTC Offer
const handleWebRTCOffer = async (params) => {
  try {
    if (!peerConnection || !params.sdp || params.type !== 'offer') {
      throw new Error('无效的WebRTC Offer')
    }
    
    // 设置远程描述
    await peerConnection.setRemoteDescription({
      type: 'offer',
      sdp: params.sdp
    })
    
    // 创建并设置本地描述
    const answer = await peerConnection.createAnswer()
    await peerConnection.setLocalDescription(answer)
    
    // 发送Answer给服务端
    await rpcClient.sendRequest('webrtc.answer', {
      type: 'answer',
      sdp: answer.sdp
    })
    
    console.log('WebRTC协商完成')
    
  } catch (error) {
    console.error('处理WebRTC Offer失败:', error)
    throw error
  }
}

// 处理WebRTC ICE候选
const handleWebRTCIceCandidate = async (params) => {
  try {
    if (!peerConnection || !params.candidate) {
      return
    }
    
    await peerConnection.addIceCandidate({
      candidate: params.candidate,
      sdpMLineIndex: params.sdpMLineIndex
    })
    
  } catch (error) {
    console.error('处理ICE候选失败:', error)
  }
}

onMounted(() => {
  searchForm.date = dayjs()
  searchForm.startTime = dayjs().hour(0).minute(0).second(0)
  searchForm.endTime = dayjs().hour(23).minute(59).second(59)
  // 初始化默认时间轴
  searchStartTime.value = dayjs().startOf('day').unix()
  searchEndTime.value = dayjs().endOf('day').unix()
  generateDefaultTimeline()
})

onUnmounted(() => {
  if (isPlaying.value) {
    stopPlayback()
  }
  
  // 清理WebSocket连接
  if (webSocket) {
    webSocket.close()
    webSocket = null
    rpcClient = null
  }
  
  // 清理WebRTC连接
  if (peerConnection) {
    peerConnection.close()
    peerConnection = null
  }
})
</script>

<style scoped>
.playback-container {
  padding: 12px;
}

.search-panel {
  height: calc(100vh - 150px);
  overflow-y: auto;
}

.player-panel {
  height: calc(100vh - 150px);
}

.compact-form {
  padding: 0;
}

.form-item-compact {
  margin-bottom: 12px;
}

.form-item-compact:last-child {
  margin-bottom: 0;
}

.search-stats {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: center;
}

.event-type-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.event-checkbox {
  margin: 0;
  font-size: 12px;
}

.video-container {
  position: relative;
  background: #000;
  border-radius: 6px;
  overflow: hidden;
}

.video-placeholder {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.placeholder-content {
  text-align: center;
  color: #999;
}

.video-player {
  position: relative;
}

.video-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 16px;
  color: white;
}

.control-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.time-info {
  font-size: 14px;
  color: #fff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.audio-status {
  display: flex;
  align-items: center;
}

.volume-control {
  display: flex;
  align-items: center;
  margin-left: 4px;
}

.volume-control :deep(.ant-slider) {
  margin: 0;
}

.volume-control :deep(.ant-slider-track) {
  background: #1890ff;
}

.volume-control :deep(.ant-slider-handle) {
  border-color: #1890ff;
  background: #1890ff;
}

.volume-control :deep(.ant-slider-handle:focus) {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.progress-row {
  margin-top: 8px;
}

.current-info {
  margin-top: 16px;
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
}

:deep(.ant-slider-track) {
  background: #1890ff;
}

:deep(.ant-slider-handle) {
  border-color: #1890ff;
}

/* 时间轴样式 */
.timeline-container {
  position: relative;
  height: 40px;
  background: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
  margin-top: 8px;
}

.timeline-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, #e8e8e8, #f5f5f5);
}

.timeline-segments {
  position: absolute;
  top: 8px;
  left: 0;
  right: 0;
  height: 16px;
  z-index: 2;
}

.timeline-segment {
  position: absolute;
  height: 100%;
  cursor: pointer;
  border-radius: 2px;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.timeline-segment:hover {
  transform: scaleY(1.2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

/* 不同录像类型的颜色 */
.segment-type-0 {
  background: linear-gradient(to bottom, #52c41a, #389e0d); /* 连续录像 - 绿色 */
}

.segment-type-1 {
  background: linear-gradient(to bottom, #1890ff, #1366cc); /* 动态检测 - 蓝色 */
}

.segment-type-2 {
  background: linear-gradient(to bottom, #ff4d4f, #cc3030); /* 报警录像 - 红色 */
}

.segment-type-3 {
  background: linear-gradient(to bottom, #faad14, #d48806); /* 手动录像 - 橙色 */
}

.timeline-progress {
  position: absolute;
  top: 0;
  width: 2px;
  height: 100%;
  background: #ff4d4f;
  z-index: 5;
  box-shadow: 0 0 4px rgba(255, 77, 79, 0.5);
}

.timeline-progress::before {
  content: '';
  position: absolute;
  top: -2px;
  left: -3px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff4d4f;
  box-shadow: 0 0 4px rgba(255, 77, 79, 0.8);
}

.timeline-scale {
  position: absolute;
  top: 24px;
  left: 0;
  right: 0;
  height: 16px;
  z-index: 1;
}

.timeline-tick {
  position: absolute;
  height: 100%;
}

.tick-mark {
  position: absolute;
  top: 0;
  left: 0;
  width: 1px;
  height: 8px;
  background: #999;
}

.tick-label {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 10px;
  color: #666;
  white-space: nowrap;
}

.timeline-interaction {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 3;
  cursor: pointer;
}

.timeline-tooltip {
  position: fixed;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  font-size: 12px;
  border-radius: 4px;
  white-space: nowrap;
  z-index: 1000;
  pointer-events: none;
}

.timeline-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 8px;
  padding: 8px;
  background: rgba(245, 245, 245, 0.5);
  border-radius: 4px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.legend-color {
  width: 16px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

/* 更新视频容器高度以适应新布局 */
.video-placeholder {
  height: 70vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.video-player video {
  width: 100%;
  height: 70vh;
  background: #000;
}
</style>